#!/bin/bash
# Launcher of "<Hebrew name> Installer.app" (HebCaptions macOS installer). UNTESTED on a real Mac.
# 1. clears the quarantine flag of the bundle (it carries the payload), 2. opens the Cocoa window through JXA (osascript -l JavaScript),
# 3. if that window cannot start (any JXA error before the window is up) falls back to plain dialogs + the same install.sh.
HERE="$(cd "$(dirname "$0")" && pwd)"
RES="$(cd "$HERE/../Resources" && pwd)"
BUNDLE="$(cd "$HERE/../.." && pwd)"
HOME_DIR="${HC_HOME:-$HOME}"
LOGDIR="$HOME_DIR/Library/Logs/HebCaptions"
DATA="$HOME_DIR/Library/Application Support/HebCaptions"
mkdir -p "$LOGDIR" "$DATA"
exec >> "$LOGDIR/launcher.log" 2>&1
echo "== launch $(date) bundle=$BUNDLE macOS=$(sw_vers -productVersion 2>/dev/null) arch=$(uname -m)"

xattr -dr com.apple.quarantine "$BUNDLE" 2>/dev/null
chmod +x "$RES/install.sh" "$RES/uninstall.sh" 2>/dev/null
export HC_RES="$RES"
. "$RES/lang.sh"
HC_LANG="$(hc_resolve_lang)"; export HC_LANG     # he|en: env HC_LANG, else the earlier install's uiLang, else the OS language
echo "ui language: $HC_LANG"
export HC_HOME="$HOME_DIR"
export HC_STATUS="${HC_STATUS:-$DATA/install_status.tsv}"
rm -f "$DATA/ui_ok"

DIALOG() { LC_ALL=en_US.UTF-8 osascript -l JavaScript "$RES/dialog.js" "$@"; }

OSA="${HC_OSASCRIPT:-osascript}"
"$OSA" -l JavaScript "$RES/installer.js"
rc=$?
echo "installer.js exit code $rc, ui_ok=$([ -f "$DATA/ui_ok" ] && echo yes || echo no)"
if [ $rc -eq 0 ] || [ -f "$DATA/ui_ok" ]; then exit 0; fi

# ---- fallback: no window. Dialogs only; same worker.
echo "falling back to the headless installer"
/bin/bash "$RES/install.sh" plan
dl="$(awk -F'\t' '$1=="info"&&$2=="download"{printf "%.1fGB", $3/1073741824}' "$HC_STATUS" 2>/dev/null)"
if ! grep -q "^result	plan" "$HC_STATUS" 2>/dev/null; then
  DIALOG text=fallback.fail buttons=fallback.ok icon=stop log="$LOGDIR/install.log" >/dev/null
  exit 1
fi
ans="$(DIALOG text=fallback.ask buttons=fallback.cancel,fallback.install default=fallback.install dl="$dl")"
[ "$ans" = "idx=1" ] || exit 0
/bin/bash "$RES/install.sh" run
if grep -q "^result	ok" "$HC_STATUS" 2>/dev/null; then
  DIALOG text=fallback.done buttons=fallback.ok >/dev/null
else
  DIALOG text=fallback.fail buttons=fallback.ok icon=stop log="$LOGDIR/install.log" >/dev/null
fi
exit 0
